package com.equipment.management.mqtt;

import com.alibaba.fastjson.JSON;
import com.equipment.management.dao.SensorDataDao;
import com.equipment.management.entity.SensorData;
import com.equipment.management.service.MainframeService;
import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.text.SimpleDateFormat;


@Configuration
@IntegrationComponentScan
@Log4j2

public class MqttReceiveConfig {

    @Autowired
    private SensorDataDao sensorDataDao;

    @Autowired
    private MainframeService mainframeService;

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout ;   //连接超时

    private MqttClient client;

    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setConnectionTimeout(10);
        mqttConnectOptions.setKeepAliveInterval(60);
        mqttConnectOptions.setAutomaticReconnect(true);
        return mqttConnectOptions;
    }
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        log.info("链接参数：【】",factory);
        return factory;
    }

    //接收通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    //配置client,监听的topic
//    @Bean
//    public MessageProducer inbound() {
//
//        //List<Mainframe> list=mainframeService.getAllmainframe();
//        //String topic_id=list.stream().map(n ->String.valueOf(n.getCode())).collect(Collectors.joining("\",\""));
//        //StringUtils.split(defaultTopic, ",");
////        MqttPahoMessageDrivenChannelAdapter adapter =
////                new MqttPahoMessageDrivenChannelAdapter(clientId+"_inbound", mqttClientFactory(),
////                        "device_pub:e0e2e6d6e1e4","device_sub:e0e2e6d6e1e4","device_pub");
//        String topic_id="111";
//        log.info("topic_id:{}",topic_id);
//        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId+"_inbound", mqttClientFactory(), topic_id);
//        adapter.setCompletionTimeout(completionTimeout);
//        adapter.setConverter(new DefaultPahoMessageConverter());
//        adapter.setQos(1);
//        adapter.setOutputChannel(mqttInputChannel());
//
//
//        return adapter;
//    }

//    //配置client,监听的topic
//    @Bean
//    public MessageProducer mqttdl() {
//
//        List<Mainframe> list=mainframeService.getAllmainframe();
//        String topic_id=list.stream().map(n ->String.valueOf(n.getCode())).collect(Collectors.joining("\",\"", "\"", "\""));
//
////        MqttPahoMessageDrivenChannelAdapter adapter =
////                new MqttPahoMessageDrivenChannelAdapter(clientId+"_inbound", mqttClientFactory(),
////                        "device_pub:e0e2e6d6e1e4","device_sub:e0e2e6d6e1e4","device_pub");
//
//        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId+"_inbound", mqttClientFactory(), topic_id);
//        adapter.setCompletionTimeout(completionTimeout);
//        adapter.setConverter(new DefaultPahoMessageConverter());
//        adapter.setQos(1);
//        adapter.setOutputChannel(mqttInputChannel());
//
//
//        return adapter;
//    }







    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
                 if("111".equalsIgnoreCase(topic)){

                    Long time = message.getHeaders().getTimestamp();
                    // 时间戳转日期格式
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = sf.format(time);
                     String msg = message.getPayload().toString();
                    log.info("MQTT信息:{} "+msg);
                    // json字符串转SensorData对象
                    SensorData sensorData = JSON.parseObject(msg,SensorData.class);
                    sensorData.setDate(date);
                     log.info("sensorData参数:{} "+sensorData);
                     // 保存到数据库
                    sensorDataDao.addData(sensorData);
                }  else   if("device_sub:e0e2e6d6e1e4".equalsIgnoreCase(topic)){

                    Long time = message.getHeaders().getTimestamp();
                    // 时间戳转日期格式
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = sf.format(time);
                    String msg = message.getPayload().toString();
                    log.info("MQTT信息:{} "+msg);
                    // json字符串转SensorData对象
                    SensorData sensorData = JSON.parseObject(msg,SensorData.class);
                    sensorData.setDate(date);
                    log.info("sensorData参数:{} "+sensorData);
                    // 保存到数据库
                    sensorDataDao.addData(sensorData);
                }
            }
        };
    }
}